/*
* Yahtzee 3.0 Client
* (c) Karl Puusepp & Tony Lepmets
* maiz & co, 2012
*/

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GamePanel extends JPanel implements ActionListener, MouseListener {
	
	private static final long serialVersionUID = 1L;
	
	JButton veereta; // "Veereta!", "Uus mäng" nupp

	JPanel dicePanel; // paneel, mis koosneb täringute piltidest
	JLabel text; // tekst mängus, "Esimene veeretus: " jne..
	
	JPanel[] diePanels;
	int[] dice; 
	int[] userSelection; // salvestab viies checkboxis tehtud valikuid, valitud = 1, valimata = 0
	int numClicks;
	
	YahtzeeClient client;
	
	GamePanel(YahtzeeClient client) {
		
		super(new GridLayout(3,0));
		this.client = client;
		
		diePanels = new JPanel[5];
		
		dice = new int[5];
		userSelection = new int[5];
		
		veereta = new JButton("Veereta!");
		veereta.setEnabled(false);
		veereta.addActionListener(this);
		
		text = new JLabel("Esimene veeretus: ");
		
		dicePanel = new JPanel(new GridLayout(0,5));
		
		for (int i = 0; i < 5; i++) {
			diePanels[i] = new JPanel();
			diePanels[i].add(client.io.createIconLabel("0.png"));
			diePanels[i].addMouseListener(this);
			dicePanel.add(diePanels[i]);
		}

		updateDicePanel();
		
		add(text);
		add(dicePanel);
		add(veereta);
		setBorder(BorderFactory.createEmptyBorder(25,25,25,25));
	}
	
	public void updateDicePanel() {
		
		for (int i = 0; i < 5; i++) {
			//kõigepealt eemaldab olemasoleva pildi i-ndalt kohalt
			diePanels[i].remove(0);
			// lisab i-ndale kohale uue täringupildi
			if (userSelection[i] == 0 || dice[i] == 0) {
				diePanels[i].add(client.io.createIconLabel(Integer.toString(dice[i]) + ".png"));
			} else {
				diePanels[i].add(client.io.createIconLabel(Integer.toString(dice[i]) + "g.png"));
			}
			dicePanel.updateUI();
		}
	}
	
	// nupu kuular
	public void actionPerformed(ActionEvent ev) {
		client.io.send(client.selectionToString()); // send dice selection when pressed
	}
	
	public void mousePressed(MouseEvent e) {
		for (int i = 0; i < 5; i++) {
			if (e.getSource() == diePanels[i]) {
				diePanels[i].remove(0);
				if (userSelection[i] == 0) {
					diePanels[i].add(client.io.createIconLabel(Integer.toString(dice[i]) + "g.png"));
					userSelection[i] = 1;
				} else {
					diePanels[i].add(client.io.createIconLabel(Integer.toString(dice[i]) + ".png"));
					userSelection[i] = 0;
				} 
				dicePanel.updateUI();
			}
		}
	}
	
	public void mouseClicked(MouseEvent e) {}
	
	public void mouseEntered(MouseEvent arg0) {}

	public void mouseExited(MouseEvent arg0) {}

	public void mouseReleased(MouseEvent arg0) {}
}
